const app = getApp()
const {Toast,viewHeight} = app.globalData
import {getFreeDoctor,updateDoctorToDoTasks} from "../../../api/wenzhen"
import {createChatRoom,updateChatRoomContent,findChatRoomContentById,findChatRoomWithUserIdAndStaffId} from "../../../api/chatRoom"
import {getUserInfo} from "../../../api/userInfo"
import {formatTime} from "../../../utils/utils"
import {send,SocketTask} from "../../../utils/socketTask"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    chatContent:[],
    tips:["皮肤疾病","咳嗽","感冒","肚子不舒服","发烧","眼睛不舒服","头晕","腹泻","头疼"],
    inputValue:"",
    viewHeight,
    chatContentBoxHeight:viewHeight - 120
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    SocketTask.onMessage(res=>{
      let {data} = res
      data = JSON.parse(data)
      // console.log("wenzhen",data);
      if(data.haveNewMsg){
        this.findContentByChatRoomId(this.data.chatRoomId)
      }
    })

    let doctorInfo = await getFreeDoctor()
    let userInfo = await getUserInfo()
    let userId = userInfo._id

    // 查找用户与医生之间是否有过聊天记录
    let ret = await findChatRoomWithUserIdAndStaffId(userId,doctorInfo._id)
    if(!ret.data){
      // 聊天室不存在
      this.setData({
        chatRoomIsExisted:ret.data
      })
    }else{
      let chatRoomId = ret.data.id
      this.setData({
        chatRoomIsExisted:true,
        chatRoomId,
      })
      // 根据id查聊天室中的content
      this.findContentByChatRoomId(chatRoomId)
    }

    this.setData({
      doctorInfo,
      userInfo,
      doctorFirstName:doctorInfo.name[0],
      userId,
      staffId:doctorInfo._id,
    })
    
  },
  // 处理标签点击
  handleClick(e){
    const {tip:inputValue} = e.currentTarget.dataset
    this.setData({
      inputValue
    })
  },

  // 发送消息
  async sendMsg(){
    const {inputValue,userId,staffId,chatRoomIsExisted} = this.data

    if (inputValue == "") {
      Toast.fail("输入内容为空")
    }else{
      // 创建聊天室
      if(!chatRoomIsExisted){
        let ret = await createChatRoom({userId,staffId})
  
        if(ret.code == 201){
          this.setData({
            chatRoomIsExisted:true,
            chatRoomId:ret.chatRoomId
          })

          await updateDoctorToDoTasks(staffId,"add")
        }
      }

      let {chatRoomId} = this.data
      // console.log(chatRoomId);
      
      // 更新content
      let updateRet = await updateChatRoomContent(chatRoomId,{
        id:userId,
        value:inputValue,
        time:formatTime(Date.now())
      })
      // console.log(updateRet);

      // 重新根据id查聊天室中的content
      if(updateRet.code == 201){
        // 通知对方与自己有新消息
        send({
          from:"user",
          haveNewMsg:true,
          chatRoomId
        })
      }
    }
  },

  // 根据id查聊天室中的content
  async findContentByChatRoomId(chatRoomId){
    let chatContent = await findChatRoomContentById(chatRoomId)
    chatContent.reverse()
    this.setData({
      chatContent,
      inputValue:""
    })
  },

  // 测试用
  async sendDoctorMsg(){
    let {chatRoomId,staffId,inputValue} = this.data
    await updateChatRoomContent(chatRoomId,{
      id:staffId,
      value:inputValue,
      time:formatTime(Date.now())
    })
  }
})